<?php
/**
 * @todo manage the attachments
 * @author iflamed@126.com
 */
class AttachAction extends BaseAction{
	/**
	 * @todo Show all attachment from id=$_get['id']
	 */
	public function showattach(){
		if(isset($_GET['id'])){
		$content_id = $_GET['id'];
		}else{
			$content_id = 1;
		}
		$Attach = M('ContentAttachment');
		$Content = M('Content');
		$content = $Content->where('content_id='.$content_id)->find();
		$attaches = $Attach->where('content_id='.$content_id)->select();
		$this->assign('attaches',$attaches);
		$this->assign('content',$content);
		$this->display();
	}
	/**
	 * @todo Add a attach for content_id=$_POST['content_id']
	 */
	public function doadd(){
		$content_id = $_POST['content_id'];
		$Content = M('Content');
		//判断是否有附件
		if (!empty($_FILES)) {
			$Content->content_attach = 1;
		}else{
			$Content->content_attach = 0;
		}
		$Content->where('content_id='.$content_id)->save();
		//上传附件
		if (!empty($_FILES)) {
			//如果有文件上传 上传附件
			$files=$this->_upload();
			$Attach = M('ContentAttachment');
			foreach ($files as $key1 => $file) {
				$data['attachment_newname'] = $file['savename'];
				$data['attachment_name'] = $file['name'];
				$data['content_id'] = $content_id;
				$data['attachment_mime'] = $file['type'];
				$isattach = $Attach->data($data)->add();
			}
			$this->redirect('showattach',array('id'=>$content_id),3,'Upload files succeed');
		}else {
			$this->redirect('showattach', array('id'=>$content_id),3,'There isn\'t a file');
		}
	}
	/**
	 * @todo Download a attachment
	 */
	public function download(){
		$attach_id = $_GET['attach'];
		$Attach = M('ContentAttachment');
		$file = $Attach->where('attachment_id='.$attach_id)->find();
		$filepath = '__APP__/../Public/Uploads/attach/'.$file['attachment_newname'];
		$filename = $file['attachment_name'];
		//header('Content-Type: application/octet-stream');
		//header("Accept-Ranges: bytes");
		//header("Accept-Length: ".filesize($filepath));
		//header('Content-Disposition: attachment; filename="' . $filename . '"');
		//readfile($filepath);
		if($filename!='')
		$this->_download($filepath, $filename);
		else
		echo "File not exits";
	}
	/**
	 *@todo delete a attach which id is $_GET['attach']
	 */
	public function deleteattach(){
		$attach_id = $_GET['attach'];
		$Attach = M('ContentAttachment');
		$Content = M('Content');
		$file = $Attach->where('attachment_id='.$attach_id)->find();
		$filepath = '__APP__/../Public/Uploads/attach/'.$file['attachment_newname'];
		$contentid = $file['content_id'];
		if(file_exists($filepath)){
			if(@unlink($filepath)){
				$Attach->where('attachment_id='.$attach_id)->delete();
				$count = $Attach->where('content_id='.$contentid)->count();
				if($count == 0){
					$thiscontent['content_attach']=0;
					$Content->where('content_id='.$contentid)->save($thiscontent);
				}
				$this->redirect('showattach', array('id'=>$contentid),4,'Delete a file');
			}else {
				$this->redirect('showattach', array('id'=>$contentid),4,'Failed to delete a file');
			}
		}else{
			$Attach->where('attachment_id='.$attach_id)->delete();
			$count = $Attach->where('content_id='.$contentid)->count();
			if($count == 0){
				$thiscontent['content_attach']=0;
				$Content->where('content_id='.$contentid)->save($thiscontent);
			}
			$this->redirect('showattach', array('id'=>$contentid),4,'File is not exits');
		}
	}
	/**
	 * Upload file
	 * Enter description here ...
	 */
	protected function _upload() {
		import("@.ORG.UploadFile");
		$upload = new UploadFile();
		//设置上传文件大小
		$upload->maxSize = 32922000;
		//设置上传文件类型
		$upload->allowExts = explode(',', 'txt,rar,zip,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid');
		//设置附件上传目录
		$upload->savePath = '__APP__/../Public/Uploads/attach/';
		//设置上传文件规则
		$upload->saveRule = 'uniqid';
		//文件同名不覆盖
		$upload->uploadReplace = FALSE;
		//使用子目录方式保存
		$upload->autoSub = TRUE;
		//子目录创建方式DATE
		$upload->subType = 'date';
		if (!$upload->upload()) {
			//捕获上传异常
			$this->error($upload->getErrorMsg());
		} else {
			//取得成功上传的文件信息
			$uploadList = $upload->getUploadFileInfo();
		}
	return $uploadList;
	}
	/**
	 * $file_path file's path include it's filename
	 * $file_name file's name include it's extension
	 * Enter description here ...
	 * @param String $file_path
	 * @param String $file_name
	 */
	protected function _download($file_path, $file_name)
	{
		$file_path = chop($file_path); // 去掉路径中多余的空格.
			
		// 判断要下载的文件是否存在.
		if(!file_exists($file_path)) {
			echo "The file <";
			echo $file_name;
			echo "> not exits。";
			return false;
		}
		$file_size = filesize($file_path);

		header("Content-type:application/octet-stream");
		header("Accept-Ranges:bytes");
		header("Accept-Length:".$file_size);
		header("Content-Transfer-Encoding: binary");
		// 以真实文件名提供给浏览器下载.
		header("Content-Disposition: attachment; filename=".$file_name);
		header("Pragma: no-cache");
			
		$fp = fopen($file_path, "rb");
		$buffer_size = 1024;
		$cur_pos = 0;
			
		while(!feof($fp) &&
		($file_size - $cur_pos) > $buffer_size) {
			$buffer = fread($fp, $buffer_size);
			echo $buffer;
			$cur_pos += $buffer_size;
		}
			
		$buffer = fread($fp, $file_size - $cur_pos);
		echo $buffer;
		fclose($fp);

		return true;
	}
}
?>